//
//  ProductListViewController.swift
//  CJXSwiftStoryboard
//
//  Created by CJX on 2016/10/20.
//  Copyright © 2016年 caijianxi. All rights reserved.
//

import UIKit
import SVProgressHUD
import MJRefresh
class ProductListViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {

    var cPathStr : String = ""
    var pageNumber :String = "1"
    var page : Int = 1
    
    var categories_name:String?
    
    
    
    let COLLECTIONVIEWCELL = "ProductCollectionCell"
    
    
    var dataArray = NSMutableArray(capacity: 0)
    
    var myCollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewLayout())
    
    
   
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        
        self.automaticallyAdjustsScrollViewInsets = false
        self.view.backgroundColor = UIColor.whiteColor()
        
        self.getData()
        self.creatView()

        
        
        

    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        sideMenuViewController()?.menuContainerView?.allowPanGesture = true
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}


extension ProductListViewController{
    private func getData(){
        self.pageNumber = String(self.page)
        let prama = ["main_page":"products_list","cPath":self.cPathStr,"page":self.pageNumber]
        NetworkTool.shareInstance.request(.GET, urlString: APIBASE, parmas: prama) { (result, error) in
            if result != nil{
//                print(result)
                let dic = (result as? NSDictionary)!["data"] as? NSDictionary
                let totalPage = dic!["total_pages"] as? NSNumber
                let array = dic!["products_list"]as?[[String:NSObject]]
                
                
               
                if self.page>Int(totalPage!){
                    SVProgressHUD.showSuccessWithStatus("Finish download data.")
                    
                }else{
                    for dict in array!{
                        let model = ProductModel(dict: dict)
                        self.dataArray.addObject(model)
                    }
                    self.myCollectionView.reloadData()
                    SVProgressHUD.showSuccessWithStatus("Load successfully!")
                }
                
                
                self.myCollectionView.mj_header.endRefreshing()
                self.myCollectionView.mj_footer.endRefreshing()
            }else{
                SVProgressHUD.showErrorWithStatus("productList error:" + String(error))
                print("productList error:" + String(error))
            }
        }
        
    }
}

extension ProductListViewController{
    private func creatView(){
        
        let leftBtn = UIButton(type: .Custom)
        leftBtn.setImage(UIImage(named: "nav_back"), forState: .Normal)
        leftBtn.frame = CGRectMake(0, 0, 30, 30)
        leftBtn.addTarget(self, action: #selector(leftBtnClick), forControlEvents: .TouchUpInside)
        let item = UIBarButtonItem(customView: leftBtn)
        self.navigationItem.leftBarButtonItem = item
        
        
        let rightItemCustomeView   = UIButton(type: UIButtonType.Custom);
        rightItemCustomeView.frame = CGRectMake(0, 0, 30, 30);
        rightItemCustomeView.setImage(UIImage(named:"nav_me"), forState: UIControlState.Normal)
        rightItemCustomeView.addTarget(self, action: #selector(BaseViewController.rightButtonAction(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightItemCustomeView);
        
        
        
        
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSizeMake((SCREEN_WIDTH-15)/2, (SCREEN_WIDTH-15)/2*1.4)
        layout.minimumInteritemSpacing = 4
        layout.minimumLineSpacing = 4
        layout.sectionInset = UIEdgeInsetsMake(5, 5, 0, 5)
        
        myCollectionView.backgroundColor = UIColor.whiteColor()
        myCollectionView.collectionViewLayout = layout
        myCollectionView.frame = CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64)
        myCollectionView.delegate = self
        myCollectionView.dataSource = self
        self.view.addSubview(myCollectionView)
        myCollectionView.registerClass(ProductListCollectionViewCell.self, forCellWithReuseIdentifier: COLLECTIONVIEWCELL)
        
        
        myCollectionView.mj_header = MJRefreshNormalHeader(refreshingBlock: { 
            SVProgressHUD.showWithStatus("Loading...")
            self.page = 1
            self.dataArray.removeAllObjects()
            self.getData()
        })
        myCollectionView.mj_footer = MJRefreshBackFooter(refreshingBlock: {
            SVProgressHUD.showWithStatus("Loading...")
            self.page = self.page + 1
            self.getData()
            
        })
        
       
        
    }
    
    func tapClick(tap:UITapGestureRecognizer){
        if sideMenuViewController()?.menuContainerView?.currentSideMenuState == KVSideMenu.SideMenuState.Right{
            self.sideMenuViewController()?.menuContainerView?.toggleRightSideMenu()
        }else{
            myCollectionView.removeGestureRecognizer(tap)
        }
    }
    
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(COLLECTIONVIEWCELL, forIndexPath: indexPath)
        let model = self.dataArray[indexPath.item]as?ProductModel
        
        (cell as? ProductListCollectionViewCell)?.model = model
        
        return cell
        
    }
    
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
//        当右侧栏出现时，点击让其回来
        if sideMenuViewController()?.menuContainerView?.currentSideMenuState == KVSideMenu.SideMenuState.Right{
            let tap = UITapGestureRecognizer(target: self, action: #selector(tapClick(_:)))
            myCollectionView.addGestureRecognizer(tap)
            return
        }
        
        let commodityVC = CommodityViewController()
        let model = self.dataArray[indexPath.item] as? ProductModel
        commodityVC.idStr = model!.products_id
        commodityVC.productImgView = model!.products_image!
        
        MobClick.event("ProductListClick", attributes: ["productName" : (model?.products_name)!])

        
        self.navigationController?.pushViewController(commodityVC, animated: true)
        
        
    }
    
    
    
    
    func leftBtnClick(){
        self.navigationController?.popViewControllerAnimated(true)
    }
    func rightButtonAction(sender: UIButton)
    {
        sender.layer.startAnimation1(tintColor :UIColor.blackColor())
        sender.layer.startAnimation1()
        NSNotificationCenter.defaultCenter().postNotificationName(KVSideMenu.Notifications.toggleRight, object: self)
        //   OR
        // self.sideMenuViewController()?.menuContainerView?.toggleRightSideMenu();
    }
}















